Django 常用命令面试题全解析
一、核心要点速览
💡 核心考点
- 项目管理: django-admin vs manage.py
- 数据库操作: makemigrations, migrate, shell
- 开发服务器: runserver, createsuperuser
- 数据管理: dumpdata, loaddata, dbshell
- 静态文件: collectstatic, findstatic
二、Django 命令体系
1. 两种命令入口
bash
# ========== django-admin(全局命令)==========
# 用于创建项目等全局操作
django-admin startproject myproject
django-admin --version
django-admin help
# ========== manage.py(项目级命令)==========
# 每个 Django 项目都有,位于项目根目录
python manage.py <command> [options]
# 或者使用(推荐)
./manage.py <command> [options]
# 常见用法
python manage.py runserver
python manage.py migrate
python manage.py createsuperuser2. 命令分类图
┌──────────────────────────────────────────────────────────┐
│ Django 命令分类 │
└──────────────────────────────────────────────────────────┘
Django Commands
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
├─ 项目管理类
│ ├─ startproject 创建新项目
│ └─ startapp 创建新应用
│
├─ 数据库类
│ ├─ makemigrations 生成迁移文件
│ ├─ migrate 执行迁移
│ ├─ showmigrations 显示迁移状态
│ ├─ dbshell 数据库命令行
│ └─ inspectdb 反向生成模型
│
├─ 数据管理类
│ ├─ dumpdata 导出数据
│ ├─ loaddata 导入数据
│ └─ flush 清空数据
│
├─ 开发调试类
│ ├─ runserver 启动开发服务器
│ ├─ shell Python 交互环境
│ ├─ check 检查错误
│ └─ test 运行测试
│
├─ 用户认证类
│ ├─ createsuperuser 创建超级用户
│ └─ changepassword 修改密码
│
├─ 静态文件类
│ ├─ collectstatic 收集静态文件
│ ├─ findstatic 查找静态文件
│ └─ runserver (自动服务静态文件)
│
└─ 其他工具类
├─ translate 翻译管理
├─ compilemessages 编译翻译
└─ custom commands 自定义命令
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━三、项目管理命令
1. 创建项目与应用
bash
# ========== 创建项目 ==========
django-admin startproject myproject
django-admin startproject myproject . # 在当前目录创建
# 项目结构
myproject/
├── manage.py
└── myproject/
├── __init__.py
├── settings.py # 项目配置
├── urls.py # URL 配置
├── asgi.py # ASGI 入口
└── wsgi.py # WSGI 入口
# ========== 创建应用 ==========
cd myproject
python manage.py startapp blog
# 应用结构
blog/
├── __init__.py
├── admin.py # 后台管理配置
├── apps.py # 应用配置
├── models.py # 数据模型
├── tests.py # 测试代码
├── views.py # 视图函数
├── migrations/ # 迁移文件
│ └── __init__.py
├── static/ # 静态文件
└── templates/ # 模板文件
# ========== 注册应用 ==========
# 在 settings.py 的 INSTALLED_APPS 中添加
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
# ...
'blog.apps.BlogConfig', # 完整路径
# 或简写
'blog',
]2. 项目结构可视化
┌──────────────────────────────────────────────────────────┐
│ Django 项目完整结构 │
└──────────────────────────────────────────────────────────┘
典型项目结构:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
myproject/
├── manage.py ← 项目管理脚本
├── requirements.txt ← 依赖列表
├── README.md ← 项目说明
├── .env ← 环境变量
│
├── config/ ← 配置目录(可选)
│ ├── __init__.py
│ ├── settings/
│ │ ├── base.py ← 基础配置
│ │ ├── development.py ← 开发配置
│ │ ├── production.py ← 生产配置
│ │ └── testing.py ← 测试配置
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py
│
├── apps/ ← 应用目录(可选)
│ ├── blog/
│ ├── shop/
│ └── api/
│
├── static/ ← 全局静态文件
│ ├── css/
│ ├── js/
│ └── images/
│
├── media/ ← 用户上传文件
│ └── uploads/
│
├── templates/ ← 全局模板
│ ├── base.html
│ └── includes/
│
└── logs/ ← 日志文件
└── debug.log
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━四、数据库操作命令
1. 迁移管理
bash
# ========== 生成迁移文件 ==========
python manage.py makemigrations
python manage.py makemigrations blog # 指定应用
python manage.py makemigrations --empty blog # 创建空迁移
# 查看详细 SQL
python manage.py sqlmigrate blog 0001
# 检查模型变化
python manage.py makemigrations --check
# ========== 执行迁移 ==========
python manage.py migrate
python manage.py migrate blog # 迁移指定应用
python manage.py migrate blog 0002 # 迁移到特定版本
python manage.py migrate blog zero # 回滚到初始状态
# 伪造迁移(不实际执行 SQL)
python manage.py migrate --fake
python manage.py migrate --fake-initial # 假设初始表已存在
# ========== 查看迁移状态 ==========
python manage.py showmigrations
python manage.py showmigrations blog
# 输出示例:
# blog
# X 0001_initial
# X 0002_article_content
# 0003_article_views
# ^ X 表示已应用,空格表示未应用2. 迁移流程图
时间 → ─────────────────────────────────────────────────►
Django 迁移工作流程:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Step 1: 修改 models.py
│
▼
Step 2: makemigrations
│
├────► 检测模型变化
│
▼
Step 3: 生成迁移文件
│ migration/
│ └── 0004_xxx.py
▼
Step 4: migrate
│
├────► 读取迁移文件
│
▼
Step 5: 执行 SQL
│ CREATE TABLE
│ ALTER COLUMN
│ ADD CONSTRAINT
▼
Step 6: 更新迁移记录
django_migrations 表
完成!✓
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━3. 数据库交互
bash
# ========== Django Shell ==========
python manage.py shell
# 在 shell 中操作
>>> from blog.models import Article
>>> Article.objects.all()
>>> Article.objects.create(title='Hello', content='World')
>>> Article.objects.filter(title__contains='Hello')
# ========== 数据库 Shell ==========
python manage.py dbshell
# 直接进入数据库命令行
# SQLite: sqlite3 db.sqlite3
# MySQL: mysql -u user -p database
# PostgreSQL: psql -U user -d database
# 执行原生 SQL
sqlite> SELECT * FROM blog_article;
mysql> SHOW TABLES;4. 数据导入导出
bash
# ========== 导出数据 ==========
python manage.py dumpdata blog > blog_data.json
python manage.py dumpdata blog.Article > articles.json
python manage.py dumpdata --format yaml > data.yaml
python manage.py dumpdata --indent 2 > pretty.json
# 导出所有数据
python manage.py dumpdata > all_data.json
# ========== 导入数据 ==========
python manage.py loaddata blog_data.json
python manage.py loaddata articles.json users.json
# 从 fixture 目录加载
python manage.py loaddata initial_data
# ========== 清空数据 ==========
python manage.py flush
# ⚠️ 警告:清空所有数据,但保留表结构五、开发服务器命令
1. runserver 详解
bash
# ========== 基本用法 ==========
python manage.py runserver
python manage.py runserver 8000 # 指定端口
python manage.py runserver 0.0.0.0:8000 # 允许外部访问
# ========== 高级选项 ==========
python manage.py runserver --noreload # 禁用自动重载
python manage.py runserver --nothreading # 禁用多线程
python manage.py runserver 0:8000 --ipv6 # IPv6
# ========== HTTPS 模式 ==========
python manage.py runserver_plus --cert-file cert.pem
# 需要 django-extensions 包2. 开发服务器对比
┌──────────────────────────────────────────────────────────┐
│ 开发服务器 vs 生产服务器 │
└──────────────────────────────────────────────────────────┘
runserver(开发):
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✓ 自动重载代码
✓ 详细的错误页面
✓ 内置调试器
✓ 不适合生产环境
✗ 单线程(默认)
✗ 性能差
✗ 不安全
适用场景:
• 本地开发
• 功能调试
• 快速原型
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Gunicorn/uWSGI(生产):
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✓ 多进程/多线程
✓ 高性能
✓ 稳定性好
✓ 安全性高
✗ 需要额外配置
✗ 无自动重载
适用场景:
• 生产环境
• 高并发场景
• 线上部署
典型配置:
gunicorn myproject.wsgi:application \
--bind 0.0.0.0:8000 \
--workers 4 \
--threads 2
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━2. 用户管理
bash
# ========== 创建超级用户 ==========
python manage.py createsuperuser
# 交互式创建
Username: admin
Email address: [email protected]
Password: ******
Superuser created successfully.
# 非交互式创建(脚本中)
python manage.py shell << EOF
from django.contrib.auth import get_user_model
User = get_user_model()
User.objects.create_superuser('admin', '[email protected]', 'password123')
EOF
# ========== 修改密码 ==========
python manage.py changepassword username
# 批量重置密码
python manage.py shell
>>> from django.contrib.auth import get_user_model
>>> User = get_user_model()
>>> user = User.objects.get(username='admin')
>>> user.set_password('newpassword')
>>> user.save()
# ========== 删除用户 ==========
python manage.py shell
>>> from django.contrib.auth import get_user_model
>>> User = get_user_model()
>>> User.objects.filter(username='test').delete()六、静态文件管理
1. collectstatic 详解
bash
# ========== 收集静态文件 ==========
python manage.py collectstatic
python manage.py collectstatic --noinput # 不提示确认
python manage.py collectstatic --clear # 先清空目标目录
python manage.py collectstatic --link # 创建符号链接(非复制)
# 查看会被收集的静态文件
python manage.py findstatic css/style.js
# ========== 配置示例 ==========
# settings.py
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles' # collectstatic 目标目录
STATICFILES_DIRS = [
BASE_DIR / 'static', # 额外的静态文件目录
]
# 收集后结构:
# staticfiles/
# ├── admin/
# ├── rest_framework/
# ├── css/
# ├── js/
# └── images/2. 静态文件查找
bash
# ========== findstatic ==========
python manage.py findstatic style.css
python manage.py findstatic admin/css/base.css
# 输出所有匹配的文件
python manage.py findstatic --all style.css
# ========== 调试静态文件问题 ==========
# 检查静态文件配置
python manage.py check --deploy
# 查看静态文件搜索路径
python manage.py shell
>>> from django.contrib.staticfiles.storage import staticfiles_storage
>>> staticfiles_storage.locations3. 静态文件处理流程
┌──────────────────────────────────────────────────────────┐
│ 静态文件处理流程 │
└──────────────────────────────────────────────────────────┘
开发环境:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
请求 /static/css/style.css
│
▼
StaticFilesHandler
│
├────► 在 STATICFILES_DIRS 中查找
├────► 在各 app/static 中查找
│
▼
返回找到的文件
✓ 自动服务静态文件
✓ 无需 collectstatic
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
生产环境:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Step 1: python manage.py collectstatic
│
├────► 收集所有静态文件
├────► 复制到 STATIC_ROOT
│
▼
Step 2: Nginx/Apache 配置
│
location /static/ {
alias /path/to/staticfiles/;
}
│
▼
Step 3: 用户请求
│
▼
Nginx 直接返回静态文件
│
✓ 高性能
✓ CDN 友好
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━七、调试与测试命令
1. 检查与调试
bash
# ========== 检查项目错误 ==========
python manage.py check
python manage.py check --deploy # 部署前检查
python manage.py check blog # 检查特定应用
# 输出示例:
# System check identified no issues (0 silenced).
# ✗ 发现问题的话会详细列出
# ========== 清除缓存 ==========
# Django 没有内置清除缓存命令
# 需要在 shell 中操作
python manage.py shell
>>> from django.core.cache import cache
>>> cache.clear()
# ========== 查看 SQL 查询 ==========
python manage.py shell
>>> from django.db import connection
>>> from blog.models import Article
>>> list(Article.objects.all())
>>> print(connection.queries_log)2. 测试相关
bash
# ========== 运行测试 ==========
python manage.py test
python manage.py test blog # 测试特定应用
python manage.py test blog.tests.test_models # 测试特定模块
python manage.py test --verbosity=2 # 详细输出
python manage.py test --keepdb # 保留测试数据库
python manage.py test --parallel # 并行执行
# ========== 测试覆盖率 ==========
# 需要 coverage 包
coverage run --source='.' manage.py test
coverage report
coverage html # 生成 HTML 报告八、高级命令与自定义
1. 自定义管理命令
python
# myapp/management/commands/hello.py
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Say hello' # 命令帮助
def add_arguments(self, parser):
parser.add_argument(
'--name',
type=str,
default='World',
help='Name to greet'
)
def handle(self, *args, **options):
name = options['name']
self.stdout.write(
self.style.SUCCESS(f'Hello, {name}!')
)
# 使用
python manage.py hello
python manage.py hello --name=Django
# myapp/management/commands/cleanup.py
from django.core.management.base import BaseCommand
from django.utils import timezone
from blog.models import Article
class Command(BaseCommand):
help = '清理过期的文章'
def handle(self, *args, **options):
expired_date = timezone.now() - timezone.timedelta(days=365)
count, _ = Article.objects.filter(
created_at__lt=expired_date
).delete()
self.stdout.write(
self.style.SUCCESS(f'Deleted {count} articles')
)
# 可以配合 crontab 定时执行
# 0 2 * * * /path/to/manage.py cleanup2. 自定义命令结构
myapp/
├── management/
│ ├── __init__.py
│ └── commands/
│ ├── __init__.py
│ ├── command1.py
│ ├── command2.py
│ └── ...
└── ...
# 命令执行流程
python manage.py command1 [options]
│
▼
management/commands/command1.py
│
▼
Command.handle() 方法九、常用命令速查表
1. 命令频率分类
┌──────────────────────────────────────────────────────────┐
│ Django 命令频率分类 │
└──────────────────────────────────────────────────────────┘
每天多次使用:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✓ runserver 启动开发服务器
✓ shell Python 交互环境
✓ makemigrations 生成迁移
✓ migrate 执行迁移
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
每周使用:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✓ createsuperuser 创建管理员
✓ test 运行测试
✓ check 检查错误
✓ collectstatic 收集静态文件
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
偶尔使用:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
• dumpdata 导出数据
• loaddata 导入数据
• dbshell 数据库命令行
• flush 清空数据
• changepassword 修改密码
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
很少使用:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
• startproject 创建项目
• startapp 创建应用
• showmigrations 查看迁移状态
• findstatic 查找静态文件
• compilemessages 编译翻译
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━2. 命令别名技巧
bash
# ========== Bash 别名 ==========
# 在 ~/.bashrc 或 ~/.zshrc 中添加
alias dj='python manage.py'
alias djr='dj runserver'
alias djs='dj shell'
alias djm='dj makemigrations'
alias djmg='dj migrate'
alias djt='dj test'
alias djc='dj check'
# 使用
dj runserver
djm && djmg
# ========== PowerShell 别名 ==========
# 在 profile.ps1 中添加
function Invoke-Django { python manage.py @args }
Set-Alias dj Invoke-Django
# 使用
dj runserver
dj shell
# ========== Makefile ==========
# 在项目根目录创建 Makefile
.PHONY: run server shell test migrate
run:
python manage.py runserver
server:
python manage.py runserver 0.0.0.0:8000
shell:
python manage.py shell
test:
python manage.py test
migrate:
python manage.py makemigrations && python manage.py migrate
collect:
python manage.py collectstatic --noinput
# 使用
make run
make migrate十、常见问题解决
1. 迁移问题
bash
# 问题 1: 迁移冲突
# 解决方案
python manage.py migrate --merge # 合并分支迁移
python manage.py makemigrations --merge # 创建合并迁移
# 问题 2: 迁移失败
# 解决方案
python manage.py migrate --fake-initial # 假设初始表已存在
python manage.py migrate app_name zero # 回滚到初始
python manage.py migrate app_name 0001 # 回滚到特定版本
# 问题 3: 检测到更改但不生成迁移
# 解决方案
python manage.py makemigrations --empty app_name # 创建空迁移
# 手动编辑生成的迁移文件2. 静态文件问题
bash
# 问题 1: 静态文件 404
# 检查清单
python manage.py findstatic css/style.css # 查找文件
python manage.py check --deploy # 检查配置
ls -la staticfiles/ # 检查是否收集
# 解决方案
python manage.py collectstatic --clear # 重新收集
# 问题 2: 静态文件未更新
# 浏览器缓存问题
python manage.py collectstatic --clear # 清空并重新收集
# 或使用版本控制
STATIC_URL = '/static/v1.2.3/'3. 数据库问题
bash
# 问题 1: 外键约束错误
# 解决方案:按正确顺序迁移
python manage.py migrate app_name zero
python manage.py migrate
# 问题 2: 数据丢失
# 预防措施
python manage.py dumpdata > backup.json # 迁移前备份
# 恢复数据
python manage.py loaddata backup.json
# 问题 3: 数据库连接失败
# 检查数据库配置
python manage.py check --deploy
python manage.py dbshell # 尝试直接连接十一、面试标准回答
Django 提供了丰富的管理命令,通过
manage.py脚本执行,涵盖了项目开发的各个方面。最常用的命令包括:
- 数据库迁移:
makemigrations生成迁移文件,migrate执行迁移- 开发服务器:
runserver启动本地开发服务器- 数据管理:
shell进入 Python 交互环境,dbshell进入数据库命令行- 用户管理:
createsuperuser创建管理员用户- 静态文件:
collectstatic收集所有静态文件到统一目录迁移命令的工作流程是:
- 修改
models.py后执行makemigrations生成迁移文件- 执行
migrate将变更应用到数据库- 使用
showmigrations查看迁移状态- 可以通过
sqlmigrate查看生成的 SQL数据导入导出使用
dumpdata和loaddata:
dumpdata可以导出为 JSON、YAML 等格式loaddata从 fixture 文件导入数据flush清空所有数据但保留表结构静态文件管理在生产环境很重要:
- 开发环境 Django 自动服务静态文件
- 生产环境需要执行
collectstatic收集到STATIC_ROOT- 通常配合 Nginx 等 Web 服务器提供静态文件服务
实际项目中,我经常使用:
shell进行数据调试和临时操作test运行自动化测试check --deploy在部署前做最后检查- 自定义命令处理定时任务和批处理操作
最佳实践是:
- 频繁执行迁移操作,保持数据库同步
- 定期备份重要数据
- 使用
--noinput参数实现自动化脚本- 编写自定义命令封装常用操作
十二、记忆口诀
Django 命令歌诀:
项目管理两大类,
startproject 建项目。
startapp 来建应用,
manage.py 是总指挥!
数据库操作:
makemigrations 生成迁移,
migrate 来执行它。
showmigrations 看状态,
dbshell 进数据库!
开发调试:
runserver 启服务,
shell 交互最方便。
createsuperuser 建管理,
collectstatic 收文件!
数据管理:
dumpdata 导数据,
loaddata 导入它。
flush 清空要小心,
备份一定要做好!
高级用法:
自定义命令很强大,
批处理任务全靠它。
Makefile 起别名,
开发效率顶呱呱!十三、推荐资源
十四、总结一句话
- 项目管理: startproject + startapp = 快速搭建项目 🏗️
- 数据库: makemigrations + migrate = 模型同步利器 🗄️
- 开发调试: runserver + shell = 日常开发必备 💻
- 数据管理: dumpdata + loaddata = 数据备份迁移 📦
- 静态文件: collectstatic = 生产部署必需 ✨